package com.lishe.lishe.lishe.module.shopingcart.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.shopingcart.bean.GoodObject;
import com.lishe.lishe.lishe.module.shopingcart.bean.ShoppingCartObject;
import com.lishe.lishe.lishe.module.shopingcart.bean.StoreObject;
import com.lishe.lishe.lishe.module.shopingcart.http.HttpShopppingCart;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ViewUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by lwa on 2017/9/7.
 */

public class ShoppingCartAdapter0 extends BaseAdapter {
    private ImageLoaderUtils imageLoaderUtils;
    private Context context;
    private ShoppingCartObject shoppingCartObject;
    private GoodObject upGoodObject = null;//修改商品数据
    private List<GoodObject> upGoodObjectList = null;//修改商品数据列表
    private List<StoreObject> storeObjectList = null;
    private StoreObject upBusinessObject = null;//修改商店数据
    private boolean isUpdata = false;//正在修改商品数量
    private int goodsCount = 1;//修改的商品数
    private String token;


    public ShoppingCartAdapter0(Context context, ShoppingCartObject shoppingCartObject) {
        this.context = context;
        token = Globals.getToken();
        this.shoppingCartObject = shoppingCartObject;
        imageLoaderUtils = new ImageLoaderUtils();
        storeObjectList = shoppingCartObject.getStoreObjects();
        Log.e("1获取到的数据ww", storeObjectList.size() + "");
    }

    public void changedata(ShoppingCartObject shoppingCartObject) {
        this.shoppingCartObject = shoppingCartObject;
        storeObjectList = shoppingCartObject.getStoreObjects();
        Log.e("2获取到的数据ww", storeObjectList.size() + "");
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return storeObjectList == null ? 0 : storeObjectList.size();
    }

    @Override
    public Object getItem(int i) {
        return storeObjectList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }


    @Override
    public View getView(final int point, View view, ViewGroup viewGroup) {
        final ShopViewHolder shopViewHolder;
        final StoreObject storeObject = shoppingCartObject.getStoreObjects().get(point);
        //--------------------商店view初始化------------------------
        if (view == null) {
            shopViewHolder = new ShopViewHolder();
            view = View.inflate(context, R.layout.item_shopping_car, null);
            shopViewHolder.initView(view);
            view.setTag(shopViewHolder);
        } else {
            shopViewHolder = (ShopViewHolder) view.getTag();
        }
        //--------------------商店------------------------
        final List<GoodObject> lisGoods = storeObject.getGoodObjects();
        shopViewHolder.businessName.setText(storeObject.getShop_name());
        if (storeObject.isCheck()) {
            shopViewHolder.shopCheckImg.setImageResource(R.mipmap.sel_check_icon);
        } else {
            shopViewHolder.shopCheckImg.setImageResource(R.mipmap.nor_check_icon);
        }
        //商店勾选
        shopViewHolder.shopCheckImg.setOnClickListener(new View.OnClickListener() {//商店商品全选
            @Override
            public void onClick(View view) {
                checkBussiness(storeObject);
            }
        });
        //--------------------商品view初始化------------------------
        shopViewHolder.goodsContent.removeAllViews();
        for (int i = 0; i < lisGoods.size(); i++) {
            final GoodsViewHolder goodsViewHolder;
            final GoodObject goodObject = lisGoods.get(i);
            View view1 = View.inflate(context, R.layout.item_shopping_car_goods, null);
            goodsViewHolder = new GoodsViewHolder();
            view1.setId(i);
            goodsViewHolder.initView(view1);
            shopViewHolder.goodsContent.addView(view1);

            //--------------------商品------------------------
            Log.e("图片地址", goodObject.getImage_default_id());
            imageLoaderUtils.displayImage(goodObject.getImage_default_id(), goodsViewHolder.goodsImg);
            goodsViewHolder.goodsCount.setText(goodObject.getQuantity() + "");
            goodsViewHolder.goodsPay.setText((int) ((float) goodObject.getPrice() * 100) + "");
            //改动后优惠价不能获取
            if (goodObject.getMkt_price() > 0) {
                goodsViewHolder.oldPay.setVisibility(View.VISIBLE);
                goodsViewHolder.oldPay.setText((int) ((float) goodObject.getMkt_price() * 100) + "积分");
            } else {
                goodsViewHolder.oldPay.setVisibility(View.GONE);
            }
            goodsViewHolder.goodsName.setText(goodObject.getTitle());
            goodsViewHolder.goodsInfo.setText(goodObject.getSpec_info());
            if (goodObject.isCheck()) {
                goodsViewHolder.goodsCheckImg.setImageResource(R.mipmap.sel_check_icon);
            } else {
                goodsViewHolder.goodsCheckImg.setImageResource(R.mipmap.nor_check_icon);
            }
            //点击商品跳到商品详情页
            goodsViewHolder.goodsLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (itemOnClickListener != null) {
                        itemOnClickListener.onItemOnClickListener(goodObject);
                    }
                }
            });
            //单个勾选
            goodsViewHolder.goodsCheckImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkGoods(goodObject, storeObject);
                }
            });
            //删除
            goodsViewHolder.delectImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    removeGoods(storeObject, lisGoods, goodObject);
                }
            });
            //加
            goodsViewHolder.augment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isUpdata) {
                        return;
                    }
                    isUpdata = true;

                    goodsCount = goodObject.getQuantity() + 1;
                    upGoodsCount(goodObject, goodsCount);
                }
            });
            //减
            goodsViewHolder.redus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isUpdata) {
                        return;
                    }
                    goodsCount = goodObject.getQuantity();
                    if (goodsCount <= 1) {
                        toast("至少要选择一件商品！");
                    } else {
                        isUpdata = true;
                        goodsCount = goodsCount - 1;
                        upGoodsCount(goodObject, goodsCount);
                    }
                }
            });
        }
        return view;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    class ShopViewHolder {

        private ImageView shopCheckImg;
        private TextView businessName;
        private LinearLayout goodsContent;

        private void initView(View v) {
            shopCheckImg = v.findViewById(R.id.check_img);
            businessName = v.findViewById(R.id.business_name);
            goodsContent = v.findViewById(R.id.goods_content);
            ViewUtils.addTouch(shopCheckImg, 15, 15, 15, 15);
        }
    }

    class GoodsViewHolder {
        private RelativeLayout goodsLayout;
        private ImageView goodsCheckImg;
        private ImageView goodsImg;
        private ImageView delectImg;
        private TextView goodsCount;
        private TextView goodsName;
        private TextView goodsInfo;
        private TextView goodsPay;
        private TextView oldPay;
        private Button augment;
        private Button redus;

        private void initView(View v) {
            goodsLayout = v.findViewById(R.id.goodsLayout);
            goodsCheckImg = v.findViewById(R.id.check_img);
            goodsImg = v.findViewById(R.id.goods_img);
            goodsName = v.findViewById(R.id.goods_name);
            goodsInfo = v.findViewById(R.id.goods_info);
            goodsPay = v.findViewById(R.id.pay);
            oldPay = v.findViewById(R.id.old_pay);
            oldPay.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            delectImg = v.findViewById(R.id.delect_img);
            goodsCount = v.findViewById(R.id.count);
            augment = v.findViewById(R.id.augment);
            redus = v.findViewById(R.id.redus);
            ViewUtils.addTouch(goodsCheckImg, 100, 100, 100, 100);
        }
    }


    /**
     * 全选按钮事件
     *
     * @param isCheckAll 全选或者反选
     * @param isCallBack 是否需要实现回调事件（刷新的时候不需要）
     */
    public void checkAll(boolean isCheckAll, boolean isCallBack) {
        if (shoppingCartObject == null) {
            return;
        }

        if (isCheckAll) {//全选
            for (StoreObject businessObject : shoppingCartObject.getStoreObjects()) {
                businessObject.setCheck(false);
                checkBussiness(businessObject);
            }
        } else {//反选
            for (StoreObject businessObject : shoppingCartObject.getStoreObjects()) {
                businessObject.setCheck(true);
                checkBussiness(businessObject);
            }
        }
        if (checkListener != null && isCallBack) {
            checkListener.onCheckListener(shoppingCartObject);
        }
        notifyDataSetChanged();
    }


    private void toast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }

    /**
     * 调用接口改变购物车数据表中的商品数量
     *
     * @param goodObject
     * @param count
     */
    private void upGoodsCount(GoodObject goodObject, int count) {
        LoadingUtils.createLoadingDialog(context, null, false);
        HttpShopppingCart.updataGoodsCountFromGoodsCart(token, goodObject.getCart_id(), count + "", upGoodsCountRespose);
        upGoodObject = goodObject;
    }

    /**
     * 从购物车把商品移除
     *
     * @param lisGoodObject
     * @param goodObject
     */
    private void removeGoods(StoreObject businessObject, List<GoodObject> lisGoodObject, GoodObject goodObject) {
        LoadingUtils.createLoadingDialog(context, context.getString(R.string.delectiing), false);
        Log.e("goodsid", goodObject.getItem_id());
        HttpShopppingCart.removeGoodsFromGoodsCart(token, goodObject.getCart_id(), removGoodsRespose);
        upGoodObject = goodObject;
        upGoodObjectList = lisGoodObject;
        upBusinessObject = businessObject;
    }


    /**
     * 修改购物车商品数量监听
     */
    AsyncHttpResponseHandler upGoodsCountRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            isUpdata = false;
            LoadingUtils.closeDialog();
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    upGoodObject.setQuantity(goodsCount);
                    if (checkListener != null && upGoodObject.isCheck()) {//改变商品数量后，是过该商品被选中，更新支付金额并通知ui
                        checkListener.onCheckListener(shoppingCartObject);
                    }
                    notifyDataSetChanged();
                } else {
                    JSONObject msg = json.optJSONObject("msg");
                    toast(msg.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            isUpdata = false;
            LoadingUtils.closeDialog();
        }
    };
    /**
     * 商品移除监听
     */
    AsyncHttpResponseHandler removGoodsRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            isUpdata = false;
            LoadingUtils.closeDialog();
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    notifyDataSetChanged();
                    removeGoodsLocal();
                    toast(context.getString(R.string.success_delect));
                } else {
                    JSONObject msg = json.optJSONObject("msg");
                    toast(msg.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            isUpdata = false;
        }
    };

    CheckListener checkListener;
    ItemOnClickListener itemOnClickListener;


    public interface CheckListener {
        void onCheckListener(ShoppingCartObject shopiShoppingCartObject);
    }

    public void setOnCheckListener(CheckListener checkListener) {
        this.checkListener = checkListener;
    }

    public interface ItemOnClickListener {
        void onItemOnClickListener(GoodObject goodObject);
    }

    public void setOnItemOnClickListener(ItemOnClickListener itemOnClickListener) {
        this.itemOnClickListener = itemOnClickListener;
    }

    /**
     * 本地删除并更新列表
     */
    private void removeGoodsLocal() {
        upGoodObjectList.remove(upGoodObject);
        if (upGoodObjectList.size() == 0) {
            shoppingCartObject.getStoreObjects().remove(upBusinessObject);
        }
        if (shoppingCartObject.getStoreObjects().size() == 0) {
            shoppingCartObject.getStoreObjects().clear();
        }
        if (checkListener != null) {
            checkListener.onCheckListener(shoppingCartObject);
        }
    }


    /**
     * 商品单选
     */
    private void checkGoods(GoodObject goodObject, StoreObject businessObject) {
        if (goodObject.isCheck()) {
            goodObject.setCheck(false);
        } else {
            goodObject.setCheck(true);
        }
        isCheckGoodsAll(businessObject);
        isCheckBusinessAll(shoppingCartObject);
    }

    /**
     * 商品单选判断是否把商店下的商品都选了
     */
    private void isCheckGoodsAll(StoreObject businessObject) {
        List<GoodObject> goods = businessObject.getGoodObjects();
        boolean isCheckAll = true;
        for (GoodObject good : goods) {
            if (!good.isCheck()) {
                isCheckAll = false;
                break;
            }
        }
        if (isCheckAll) {
            businessObject.setCheck(true);
        } else {
            businessObject.setCheck(false);
        }
        if (checkListener != null) {
            checkListener.onCheckListener(shoppingCartObject);
        }
        this.notifyDataSetChanged();
    }

    /**
     * 判断是否把购物车下的商品都选了
     */
    private void isCheckBusinessAll(ShoppingCartObject shoppingcarObject) {

        boolean isCheckAll = true;
        for (StoreObject bussiBusinessObject : shoppingcarObject.getStoreObjects()) {
            if (!bussiBusinessObject.isCheck()) {
                isCheckAll = false;
                break;
            }
        }
        if (isCheckAll) {
            shoppingcarObject.setCheck(true);
        } else {
            shoppingcarObject.setCheck(false);
        }
        if (checkListener != null) {
            checkListener.onCheckListener(shoppingCartObject);
        }
        this.notifyDataSetChanged();
    }

    /**
     * 商铺选择
     */
    private void checkBussiness(StoreObject businessObject) {
        List<GoodObject> goods = businessObject.getGoodObjects();
        if (businessObject.isCheck()) {//直接点击商店全选
            businessObject.setCheck(false);
            for (GoodObject good : goods) {
                good.setCheck(false);
            }
        } else {//直接点击商店反选
            businessObject.setCheck(true);
            for (GoodObject good : goods) {
                good.setCheck(true);
            }
        }
        isCheckBusinessAll(shoppingCartObject);
        this.notifyDataSetChanged();
    }
}
